<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>聊天系统</title>
  <style>

  </style>
</head>
<body>
<form>
  <label>
    <input type="text">
  </label>
  <button>发送</button>
  <ul></ul>
</form>
<!--引入socket.io-->
<script src="socket.io/socket.io.js"></script>
<script>
  const socket = io()
  const form = document.querySelector('form')
  const input = document.querySelector('input')
  const ul = document.querySelector('ul')

  // 监听表单的提交事件
  form.addEventListener('submit', function (e) {
    // 阻止默认行为
    e.preventDefault()
    if (input.value) {
      socket.emit('chat message', input.value)
      input.value = Math.floor(Math.random() * 10012).toString()
    }
  })

  socket.on('chat message', function (msg) {
    const li = document.createElement('li')
    li.textContent = msg
    ul.appendChild(li)
  })
</script>
</body>
</html>
